package com.wnxy.carlusermanageassembly.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wnxy.carl.commons.DateUtil;
import com.wnxy.carl.dto.MyMessageDTO;
import com.wnxy.carl.dto.RegisterDTO;
import com.wnxy.carl.dto.UserDTO;
import com.wnxy.carl.exception.DemoRuntimeException;
import com.wnxy.carl.param.*;
import com.wnxy.carl.response.Result;
import com.wnxy.carlusermanageassembly.entity.User;
import com.wnxy.carlusermanageassembly.mapper.UserMapper;
import com.wnxy.carlusermanageassembly.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author Lucas
 * @since 2021-11-12
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private StringRedisTemplate srt;
    //账号登陆
    public UserDTO accountLogin(PasswordParam passwordParam){
        log.info("开始执行账号登陆：参数= {}",passwordParam);
        User user = findAccount(passwordParam.getAccount());
        if (null == user) {
            throw new DemoRuntimeException("账号不存在");
        }
        if (!user.getPassword().equals(passwordParam.getPassword())) {
            throw new DemoRuntimeException("密码不正确");
        }
        UserDTO userParam = updateLoginSuccess(user,User.LOGIN_ACCOUNT);//修改登陆成功后的数据
        return userParam;
    }

    //登陆成功后修改登陆参数修改
    private UserDTO updateLoginSuccess(User user,String loginType){
        log.info("登陆成功修改状态：参数={},{}",user,loginType);
        Long systemTimeStamp = DateUtil.getSystemTimeStamp();
        user.setUserLoginTime(systemTimeStamp);
        user.setUserLoginType(loginType);
        userMapper.updateById(user);
        UserDTO userParam = new UserDTO();
        BeanUtils.copyProperties(user, userParam);
        return userParam;
    }
    //手机号登陆
    public UserDTO phoneLogin(ShortMessageParam messageParam){
        log.info("开始执行手机号登陆：参数= {}",messageParam);
        chekeCode(messageParam.getCode(),messageParam.getPhone());
        User user = findPhone(messageParam.getPhone());
        if (null == user) {
            throw new DemoRuntimeException("手机号不正确");
        }
        UserDTO userDTO = updateLoginSuccess(user,User.LOGIN_PHONE);//修改登陆时间
        return userDTO;
    }

    //手机号发送验证码
    public String phoneCode(String phone){
        log.info("开始执行手机号发送验证码：参数= {}",phone);
        User user = findPhone(phone);
        String code = ((int)(Math.random()*9)+1)+""+(int)(Math.random()*10)+""+(int)(Math.random()*10)+""+(int)(Math.random()*10);;
        System.out.println("手机验证码："+code);
        srt.opsForValue().set("code:user:" + phone,code,300, TimeUnit.SECONDS);
        return code;
    }

    //检验验证码
    public void chekeCode(String code,String phone){
        log.info("开始执行手机验证码比较：参数= {},{}",code,phone);
        String rCode = srt.opsForValue().get("code:user:" + phone);
        if (null == rCode) {
            throw new DemoRuntimeException("验证码已过期");
        }
        if(!code.equals(rCode)){
            throw new DemoRuntimeException("验证码不正确");
        }
    }
    //身份证号查询
    public User chekeIdCard(String idCard){
        log.info("开始执行手机验证码比较：参数= {}",idCard);
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("user_idcard",idCard);
        User user = userMapper.selectOne(qw);
        return user;
    }

    //账号查询
    public User findAccount(String account){
        log.info("开始执行账号是否存在：参数= {}",account);
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("account",account);
        User user = userMapper.selectOne(qw);
        return user;
    }
    //用户名查询
    public User findUserName(String userName){
        log.info("开始执行用户名是否存在：参数= {}",userName);
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("user_name",userName);
        User user = userMapper.selectOne(qw);
        return user;
    }
    //id查询返回UserDTO
    public UserDTO findUserById(Integer userId){
        log.info("开始执行获取用户信息：参数= {}",userId);
        User user = findUserId(userId);
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user,userDTO);
        return userDTO;
    }
    //id查询返回User
    public User findUserId(Integer userId){
        log.info("id查询返回User：参数= {}",userId);
        User user = userMapper.selectById(userId);
        if (null == user){
            throw new DemoRuntimeException("没有这个用户");
        }
        return user;
    }
    //手机号查询
    public User findPhone(String phone){
        log.info("开始执行手机号是否存在：参数= {}",phone);
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("user_phone",phone);
        User user = userMapper.selectOne(qw);
        return user;
    }
    //注册账号
    public RegisterDTO register(RegisterParam registerParam){
        log.info("开始执行注册账号：参数={}",registerParam);
        User phone = findPhone(registerParam.getPhone());
        if (null != phone){
            throw new DemoRuntimeException("该手机号已存在");
        }
        chekeCode(registerParam.getCode(),registerParam.getPhone());
        User user = new User();
        user.setAccount(registerParam.getPhone());
        user.setUserPhone(registerParam.getPhone());
        user.setPassword(registerParam.getPassword());
        int insert = userMapper.insert(user);
        if (insert == 0){
            throw new DemoRuntimeException("注册失败");
        }
        RegisterDTO registerDTO = new RegisterDTO();
        BeanUtils.copyProperties(user,registerDTO);
        return registerDTO;
    }
    //修改密码
    public void amendPassword(AmendPasswordParam amendPasswordParam) {
        log.info("开始执行修改密码：参数={}",amendPasswordParam);
        if (!amendPasswordParam.getNewPassword().equals(amendPasswordParam.getUsedPassword())){
            throw new DemoRuntimeException("密码不一致");
        }
        UpdateWrapper<User> uw = new UpdateWrapper<>();
        uw.set("password",amendPasswordParam.getUsedPassword());
        uw.eq("user_id",amendPasswordParam.getUserId());
        int update = userMapper.update(null, uw);
        if (update == 0) {
            throw new DemoRuntimeException("修改失败");
        }

    }
    //修改我的信息
    public MyMessageDTO amendMessage(AmendMessageParam amendMessageParam){
        log.info("开始执行修改我的信息：参数={}",amendMessageParam);
        User user = findUserId(amendMessageParam.getUserId());
        BeanUtils.copyProperties(amendMessageParam,user);
        int i = userMapper.updateById(user);
        if (i == 0){
            throw new DemoRuntimeException("修改失败");
        }
        MyMessageDTO myMessageDTO = new MyMessageDTO();
        BeanUtils.copyProperties(user,myMessageDTO);
        return myMessageDTO;

    }
    //修改积分，状态， UserDTO
    public UserDTO andminAmendUser(AndminAmendParam andminAmendParam) {
        log.info("开始执行修改积分，状态功能：参数= {}",andminAmendParam);
        User user = findUserId(andminAmendParam.getUserId());
        BeanUtils.copyProperties(andminAmendParam,user);
        int i = userMapper.updateById(user);
        if (i == 0){
            throw new DemoRuntimeException("修改失败");
        }
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user,userDTO);
        return userDTO;
    }
    //管理员查询用户信息 UserDTO
    public UserDTO andminSeeUser(Integer userId) {
        log.info("管理员查询用户信息功能：参数= {}",userId);
        return null;
    }
}
